package com.isunland.managesystem.ui;

import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.TextView;
import com.android.volley.VolleyError;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.isunland.managesystem.R;
import com.isunland.managesystem.adapter.CompanyForumTypeAdapter;
import com.isunland.managesystem.base.BaseListFragment;
import com.isunland.managesystem.common.ApiConst;
import com.isunland.managesystem.common.VolleyResponse;
import com.isunland.managesystem.entity.CompanyForumType;
import com.isunland.managesystem.entity.SuccessMessage;
import com.isunland.managesystem.utils.LogUtil;
import com.isunland.managesystem.utils.MyUtils;
import com.isunland.managesystem.utils.ParamsNotEmpty;
import com.isunland.managesystem.utils.SharedPreferencesUtil;
import com.isunland.managesystem.utils.ToastUtil;
import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import org.json.JSONException;

/**
 * 对象功能:
 * 开发公司: 北京信普达系统工程有限公司
 * 开发人员: HuXiaoDan
 * 创建时间: 2017/4/7 13:19
 */
public class AgricultureCircleFragment extends BaseListFragment {
  private CompanyForumTypeAdapter mAdapter;
  private EditText etAgricultureCirc;
  private AlertDialog dialog;
  private String cropType;

  @Override public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setBack(true);
    if ("02".equalsIgnoreCase(
        SharedPreferencesUtil.getString(mActivity, SharedPreferencesUtil.KEY_FORUM_SUBCODE, ""))) {
      setTitleCustom("农机服务圈");
    }
    if ("01".equalsIgnoreCase(
        SharedPreferencesUtil.getString(mActivity, SharedPreferencesUtil.KEY_FORUM_SUBCODE, ""))) {
      setTitleCustom("农作物圈");
    }

    cropType = "";
  }

  @Override public void onViewCreated(View view, Bundle savedInstanceState) {
    super.onViewCreated(view, savedInstanceState);
    View header =
        getLayoutInflater(savedInstanceState).inflate(R.layout.header_search_friend, null, false);
    etAgricultureCirc = (EditText) header.findViewById(R.id.et_search_searchPersonHeader);
    etAgricultureCirc.setHint(R.string.agricultureCircleHint);
    TextView tvSearch = (TextView) header.findViewById(R.id.tv_search);
    mListview.addHeaderView(header);
    tvSearch.setOnClickListener(new View.OnClickListener() {
      @Override public void onClick(View view) {
        if (!TextUtils.isEmpty(etAgricultureCirc.getText().toString())) {
          // 农作物圈名模糊搜索
          //cropType = etAgricultureCirc.getText().toString();
          //volleyPost();

          //只允许搜索二级,跳转到二级
          cropType = etAgricultureCirc.getText().toString();
          CompanyForumType item = new CompanyForumType();
          item.setName(cropType);
          Intent intent = new Intent(getActivity(), AgricultureServiceSecondActivity.class);
          intent.putExtra(AgricultureServiceSecondFragment.EXTRA_VALUE, item);
          intent.putExtra(AgricultureServiceSecondFragment.EXTRA_FFROM,
              AgricultureServiceSecondFragment.QUERY);
          startActivity(intent);
        } else {
          ToastUtil.show(R.string.agricultureCircleHint);
        }
      }
    });
  }

  @Override public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
    inflater.inflate(R.menu.menu_add, menu);
  }

  @Override public boolean onOptionsItemSelected(MenuItem item) {
    switch (item.getItemId()) {
      case android.R.id.home:
        getActivity().finish();
        return true;
      case R.id.menu_item_add:
        //添加农作物圈
        showDialog();
        return true;
      default:
        return super.onOptionsItemSelected(item);
    }
  }

  private void showDialog() {
    final View view = LayoutInflater.from(getActivity()).inflate(R.layout.fragment_edit_text, null);
    final EditText etname = (EditText) view.findViewById(R.id.et_name);
    dialog = new AlertDialog.Builder(getActivity()).setTitle(R.string.agricultureCircleHint)
        .setView(view)
        .setPositiveButton(R.string.confirm, new DialogInterface.OnClickListener() {
          @Override public void onClick(DialogInterface dialogInterface, int i) {

            volleyPostAdd(etname.getText().toString());
          }
        })
        .setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() {
          @Override public void onClick(DialogInterface dialogInterface, int i) {
            dialog.dismiss();
          }
        })
        .create();
    dialog.show();
  }

  private void volleyPostAdd(String name) {
    if (TextUtils.isEmpty(name)) {
      ToastUtil.show(R.string.agricultureCircleHint);
      return;
    }
    String url = ApiConst.getAbsoluteUrl(ApiConst.URL_CROPTYPE_ADD);
    ParamsNotEmpty params = new ParamsNotEmpty();
    params.put("cropName", name);
    params.put("subCode",
        SharedPreferencesUtil.getString(mActivity, SharedPreferencesUtil.KEY_FORUM_SUBCODE, ""));
    MyUtils.showDialogLoading(getActivity());
    mActivity.volleyPost(url, params.getParams(), new VolleyResponse() {
      @Override public void onVolleyError(VolleyError arg0) {

      }

      @Override public void onVolleyResponse(String arg0) throws JSONException {

        MyUtils.dismissDialog();
        dialog.dismiss();
        try {
          SuccessMessage successsMessage = new Gson().fromJson(arg0, SuccessMessage.class);

          String successType = successsMessage.getResult();

          if (successType.equals("1")) {
            ToastUtil.show("添加成功,正在审核中!");
          } else {
            ToastUtil.show(R.string.failure_operation);
          }
        } catch (Exception e) {
          LogUtil.e("error", e);
          ToastUtil.show(R.string.failure_operation);
        }
      }
    });
  }

  @Override public String getUrl() {
    return ApiConst.URL_FIRST_LIST;
  }

  @Override public HashMap<String, String> getparameters() {
    ParamsNotEmpty params = new ParamsNotEmpty();
    params.put("dictFlg", "topicKindDataWJ");
    String subCode =
        SharedPreferencesUtil.getString(mActivity, SharedPreferencesUtil.KEY_FORUM_SUBCODE, "");
    params.put("subCode", subCode);
    //params.put("cropType", cropType);
    return params.getParams();
  }

  @Override public void resolveResponse(String json) {
    Type listType = new TypeToken<ArrayList<CompanyForumType>>() {
    }.getType();
    List<CompanyForumType> mForumType =
        new Gson().<ArrayList<CompanyForumType>>fromJson(json, listType);
    setAdapter(mForumType);
  }

  private void setAdapter(List<CompanyForumType> forumType) {
    if (forumType == null) {
      forumType = new ArrayList<>();
    }
    mAdapter = new CompanyForumTypeAdapter(getActivity(), forumType, false);//一级圈子显示header默认不为空
    setListAdapter(mAdapter);
    ((CompanyForumTypeAdapter) getListAdapter()).notifyDataSetChanged();
  }

  @Override public void onListItemClick(ListView l, View v, int position, long id) {
    //跳转到二级大豆,玉米详情列表
    //避免点击header时的getitem出现-1的情况.
    if (position < mListview.getHeaderViewsCount()) return;
    CompanyForumType item = mAdapter.getItem(position - mListview.getHeaderViewsCount());
    Intent intent = new Intent(getActivity(), AgricultureServiceSecondActivity.class);
    intent.putExtra(AgricultureServiceSecondFragment.EXTRA_VALUE, item);
    intent.putExtra(AgricultureServiceSecondFragment.EXTRA_FFROM,
        AgricultureServiceSecondFragment.ALL);
    startActivity(intent);
    super.onListItemClick(l, v, position, id);
  }
}
